package com.bilin.coin.tools;


import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bilin.coin.R;
import com.bilin.coin.common.adapter.CommonAdapter;
import com.bilin.coin.common.base.BaseAppCompatActivity;
import com.bilin.coin.network.RequestUtils;
import com.bilin.coin.network.RetrofitConfig;
import com.bilin.coin.network.callback.CommonCallBack;
import com.bilin.coin.utils.DensityUtils;
import com.bilin.coin.utils.DialogUtils;
import com.bilin.coin.utils.SpacesItemDecoration;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.android.material.appbar.AppBarLayout;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;



public abstract class AbsHeadRecycleViewActivity<T> extends BaseAppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.recycle)
    protected RecyclerView recyclerView;
    @BindView(R.id.ll_head)
    LinearLayout ll_head;
    @BindView(R.id.sw_refresh)
    public SwipeRefreshLayout swipeRefresh;
    @BindView(R.id.appbar_layout)
    AppBarLayout appBarLayout;

    protected int page = 1;
    protected int pageSize = 10;
    protected int totalCount;
    protected int totalPageSize;
    protected List<T> dataList = new ArrayList<>();
    protected CommonAdapter adapter;

    protected boolean enableRefresh = true;
    protected boolean isRefresh = false;

    @Override
    protected void initView() {
        ll_head.addView(fillHeadView(), new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        init();

    }
    private void init() {
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary, R.color.green_1, R.color.red_btn_bg_color, R.color.black999);
        if (!enableRefresh) swipeRefresh.setEnabled(false);
        initAdapter();
        //swipeRefresh.setRefreshing(true);
        pageSize = fillPageSize();
        if (isLoadFirst()) {
            refresh(true);
        }
    }

    protected boolean isLoadFirst() {
        return true;
    }

    private void initAdapter() {
        adapter = createAdapter();
        adapter.openLoadAnimation(fillAnimationType());
        adapter.setNotDoAnimationCount(2);
        recyclerView.setLayoutManager(fillLayoutManger());
        adapter.setOnLoadMoreListener(this, recyclerView);
        adapter.disableLoadMoreIfNotFullPage();
        adapter.setEmptyView(fillEmptyView());
        recyclerView.setAdapter(adapter);
        //设置样式刷新显示的位置
        swipeRefresh.setProgressViewOffset(true, -20, 100);
        swipeRefresh.setOnRefreshListener(this);
        //解决滑动冲突
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

                if (verticalOffset >= 0) {
                    swipeRefresh.setEnabled(true);
                } else {
                    swipeRefresh.setEnabled(false);

                }
            }
        });
    }

    protected RecyclerView.LayoutManager fillLayoutManger() {
      /*  LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(RecyclerView.VERTICAL);
        DividerItemDecoration decor = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        decor.setDrawable(ContextCompat.getDrawable(this,R.drawable.custom_divider));
        recyclerView.addItemDecoration(decor);
        return manager;*/

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.addItemDecoration(new SpacesItemDecoration(1, DensityUtils.dp2px(this, 0), 0x2000));
        return manager;
    }

    protected int fillAnimationType() {
        return BaseQuickAdapter.SLIDEIN_BOTTOM;
    }

    private CommonAdapter<T> createAdapter() {
        CommonAdapter commonAdapter = new CommonAdapter<T>(fillItemLayout(), dataList) {
            @Override
            protected void convert(BaseViewHolder helper, T item) {
                convertItem(helper,item);
            }
        };
        return commonAdapter;
    }
    protected abstract void convertItem(BaseViewHolder helper, T item);

    protected abstract int fillItemLayout();
    public abstract int fillPageSize();

    public abstract boolean isPost();

    public abstract String fillUrl();
    protected abstract View fillHeadView();
    public abstract Map<String, String> fillParams();
    public abstract List<T> parseListDataAndFillTotal(String dataJson);
    protected View fillEmptyView() {
        return View.inflate(this,R.layout.empty_view_no_data,null);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_common_head_recycle;
    }

    @Override
    public void onRefresh() {
        refresh(true);
        refreshFragmentOrHead();
    }

    protected abstract void refreshFragmentOrHead();

    private void getDataList() {
        if(isPost()) {
            RequestUtils
                    .post()
                    .url(fillUrl())
                    .params(fillParams())
                    .build()
                    .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new CommonCallBack() {
                        @Override
                        protected void onError(String errorMsg) {
                            error(errorMsg);
                        }
                        @Override
                        protected void onSuccess(String dataJson) {
                            List<T> data = parseListDataAndFillTotal(dataJson);
                            totalPageSize = totalCount / pageSize;
                            if (totalCount % pageSize > 0) {
                                totalPageSize += 1;
                            }
                            if (isRefresh) {
                                page = 1;
                                adapter.setNewData(data);
                            } else {
                                adapter.addData(data);
                            }
                            if (data.size() <= 0) {
                                //adapter.setEmptyView(R.layout.empty_view_no_data, (ViewGroup) recyclerView.getParent());
                                adapter.setEmptyView(fillEmptyView());
                            }
                            if (totalCount < minSize()) {
                                //去掉第一次进入页面进行底部刷新
                                adapter.disableLoadMoreIfNotFullPage();
                            } else {
                                adapter.loadMoreComplete();
                            }
                            page++;
                            swipeRefresh.setRefreshing(false);
                            DialogUtils.dismissDialogLoading();
                        }

                        @Override
                        protected void onCallBackError(Throwable e) {
                            adapter.loadMoreFail();
                            swipeRefresh.setRefreshing(false);
                            showMsg(e);
                            DialogUtils.dismissDialogLoading();
                        }

                        @Override
                        protected void onStopRefresh() {
                            swipeRefresh.setRefreshing(false);
                            DialogUtils.dismissDialogLoading();
                        }
                    });
        } else {
            RequestUtils
                    .get()
                    .url(fillUrl())
                    /* .addParams("pageNum", page+"")
                     .addParams("pageSize", pageSize+"")*/
                    .params(fillParams())
                    .build()
                    .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new CommonCallBack() {
                        @Override
                        protected void onError(String errorMsg) {
                            error(errorMsg);
                        }
                        @Override
                        protected void onSuccess(String dataJson) {
                            List<T> data = parseListDataAndFillTotal(dataJson);
                            totalPageSize = totalCount / pageSize;
                            if (totalCount % pageSize > 0) {
                                totalPageSize += 1;
                            }
                            if (isRefresh) {
                                page = 1;
                                adapter.setNewData(data);
                            } else {
                                adapter.addData(data);
                            }
                            if (data.size() <= 0) {
                                //adapter.setEmptyView(R.layout.empty_view_no_data, (ViewGroup) recyclerView.getParent());
                                adapter.setEmptyView(fillEmptyView());
                            }
                            if (totalCount < minSize()) {
                                //去掉第一次进入页面进行底部刷新
                                adapter.disableLoadMoreIfNotFullPage();
                            } else {
                                adapter.loadMoreComplete();
                            }
                            page++;
                            swipeRefresh.setRefreshing(false);
                            DialogUtils.dismissDialogLoading();
                        }

                        @Override
                        protected void onCallBackError(Throwable e) {
                            adapter.loadMoreFail();
                            swipeRefresh.setRefreshing(false);
                            showMsg(e);
                            DialogUtils.dismissDialogLoading();
                        }

                        @Override
                        protected void onStopRefresh() {
                            swipeRefresh.setRefreshing(false);
                            DialogUtils.dismissDialogLoading();
                        }
                    });
        }
    }

    private void error(String errorMsg) {
        showToast(errorMsg);
        swipeRefresh.setRefreshing(false);
        DialogUtils.dismissDialogLoading();
    }

    public int minSize() {
        return 10;
    }

    @Override
    public void onLoadMoreRequested() {
        if (page > totalPageSize) {
            adapter.loadMoreEnd(false);
        } else {
            refresh(false);
        }
    }

    public void refresh(boolean isRefresh) {
        //adapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        this.isRefresh = isRefresh;
        if (isRefresh) {
            page = 1;
            pageSize = fillPageSize();
        }
        getDataList();
    }

    protected void jumpArticle(String id) {
        baseStartActivityWith("/common/WebPageLoading")
                .withString("url", RetrofitConfig.newsUrl+id)
                .withString("title", "文章详情").navigation();
    }

    protected void jumpArticle(String id, String title) {
        baseStartActivityWith("/common/WebPageLoading")
                .withString("url", RetrofitConfig.newsUrl+id)
                .withString("title",title).navigation();
    }
}
